package com.example.demofx.master;

import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

import java.sql.*;
import java.time.LocalDate;
import java.util.*;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class ContactManager {
    // 使用相对路径拼接数据库连接 URL
    private final String DB_URL = "jdbc:sqlite:" + System.getProperty("user.dir") + "/identifier.sqlite";
    private ObservableList<Contact> contacts = FXCollections.observableArrayList();// 内存中的联系人列表

    public ContactManager() {
        initializeDatabase();
        loadContacts(); // 加载数据库中的联系人到内存
    }

    // 初始化数据库表
    private void initializeDatabase() {
        try (Connection conn = DriverManager.getConnection(DB_URL)) {
            Statement stmt = conn.createStatement();
            // 创建 groups 表
            stmt.execute("""
                CREATE TABLE IF NOT EXISTS groups (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL UNIQUE
                );
                """);
            // 创建 contacts 表
            stmt.execute("""
                CREATE TABLE IF NOT EXISTS contacts (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL,
                    phone TEXT,
                    mobile TEXT NOT NULL,
                    photo_path TEXT,
                    email TEXT,
                    im_WeChat TEXT,
                    im_QQ TEXT,
                    im_red_book TEXT,
                    im_TikTok TEXT,
                    im_Weibo TEXT,
                    workplace TEXT,
                    home_address TEXT,
                    postal_code TEXT,
                    birthday TEXT,
                    photo BLOB,
                    company TEXT,
                    address TEXT,
                    notes TEXT,
                    starred INTEGER DEFAULT 0 CHECK (starred IN (0, 1)) -- 是否收藏
                );
                """);
            // 创建中间表 contact_group_mapping
            stmt.execute("""
                CREATE TABLE IF NOT EXISTS contact_group_mapping (
                    contact_id INTEGER NOT NULL,
                    group_id INTEGER NOT NULL,
                    PRIMARY KEY (contact_id, group_id),
                    FOREIGN KEY (contact_id) REFERENCES contacts(id) ON DELETE CASCADE,
                    FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE
                );
                """);
            // 检查是否需要添加新列
            addMissingColumnsIfNecessary(stmt);
            // 创建索引
            stmt.execute("CREATE INDEX IF NOT EXISTS idx_contacts_starred ON contacts(starred);");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 检查并添加缺失的列
    private void addMissingColumnsIfNecessary(Statement stmt) throws SQLException {
        try {
            stmt.execute("SELECT im_WeChat FROM contacts LIMIT 1;");
        } catch (SQLException e) {
            stmt.execute("ALTER TABLE contacts ADD COLUMN im_WeChat TEXT;");
        }
        try {
            stmt.execute("SELECT im_QQ FROM contacts LIMIT 1;");
        } catch (SQLException e) {
            stmt.execute("ALTER TABLE contacts ADD COLUMN im_QQ TEXT;");
        }
        try {
            stmt.execute("SELECT im_red_book FROM contacts LIMIT 1;");
        } catch (SQLException e) {
            stmt.execute("ALTER TABLE contacts ADD COLUMN im_red_book TEXT;");
        }
        try {
            stmt.execute("SELECT im_TikTok FROM contacts LIMIT 1;");
        } catch (SQLException e) {
            stmt.execute("ALTER TABLE contacts ADD COLUMN im_TikTok TEXT;");
        }
        try {
            stmt.execute("SELECT im_Weibo FROM contacts LIMIT 1;");
        } catch (SQLException e) {
            stmt.execute("ALTER TABLE contacts ADD COLUMN im_Weibo TEXT;");
        }
    }

    // 创建联系人
    // @return 成功返回true，失败返回false
    public boolean createContact(Contact contact) {
        if (contact == null || contact.getName() == null || contact.getMobile() == null) {
            throw new IllegalArgumentException("联系人姓名和手机号码不能为空");}
        String sql = """
            INSERT INTO contacts (name, phone, mobile, email, im_WeChat, im_QQ, im_red_book, im_TikTok, im_Weibo, company, address, postal_code, birthday, notes, starred, photo_path)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
            """;
        // 执行数据库插入操作
        try (Connection conn = DriverManager.getConnection(DB_URL);
             PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            // 按索引顺序设置SQL参数
            pstmt.setString(1, contact.getName());
            pstmt.setString(2, contact.getPhone());
            pstmt.setString(3, contact.getMobile());
            pstmt.setString(4, contact.getEmail());
            pstmt.setString(5, contact.getWechat());
            pstmt.setString(6, contact.getQQ());
            pstmt.setString(10, contact.getCompany());
            pstmt.setString(11, contact.getHomeAddress());
            pstmt.setString(12, contact.getPostalCode());
            pstmt.setString(13, contact.getBirthday() != null ? contact.getBirthday().toString() : null);
            pstmt.setString(14, contact.getRemark());
            pstmt.setBoolean(15, contact.isStarred());
            pstmt.setString(16, contact.getPhotoPath());
            // 执行更新并获取受影响行数
            int rowsAffected = pstmt.executeUpdate();
            // 处理自增主键并刷新数据
            if (rowsAffected > 0) {
                ResultSet rs = pstmt.getGeneratedKeys();
                if (rs.next()) {
                    contact.setId(rs.getInt(1));
                }
                loadContacts(); // 重新加载数据
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    // 删除联系人根据ID删除指定联系人
    // @return成功返回true，失败返回false
    public boolean deleteContact(int id) {
        String sql = "DELETE FROM contacts WHERE id = ?";
        try (Connection conn = DriverManager.getConnection(DB_URL);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, id);
            int rowsAffected = pstmt.executeUpdate();
            if (rowsAffected > 0) {
                loadContacts(); // 重新加载数据
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
    // 更新联系人（基本信息和分组关系）
    //  @param contact 待更新的联系人对象，必须包含有效的ID
    public boolean updateContact(Contact contact) {
        if (contact == null || contact.getId() == 0) {
            throw new IllegalArgumentException("联系人对象或 ID 不能为空");
        }
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(DB_URL);
            conn.setAutoCommit(false);
            // 1. 更新联系人基本信息
            if (!updateBaseInfo(conn, contact)) {
                conn.rollback();
                System.err.println("错误：!updateBaseInfo(conn, contact");
                return false;
            }
            // 2. 更新分组关系
            updateGroupRelations(conn, contact);
            conn.commit();
            System.out.println("联系人更新成功，准备通知监听器");
            notifyContactUpdate(contact);
            return true;
        } catch (SQLException e) {
            try { if (conn != null) conn.rollback(); } catch (SQLException ex) {}
            e.printStackTrace();
            System.err.println("错误：catch (SQLException e) ");
            return false;
        } finally {
            try { if (conn != null) conn.close(); } catch (SQLException e) {}
        }
    }

    // 作用：更新联系人基本信息（数据库操作,不涉及分组关系）
    private boolean updateBaseInfo(Connection conn, Contact contact) throws SQLException {
        String sql = """
            UPDATE contacts SET 
                name = ?, phone = ?, mobile = ?, email = ?,
                im_WeChat = ?, im_QQ = ?, im_red_book = ?, im_TikTok = ?,
                im_Weibo = ?, company = ?, address = ?, postal_code = ?,
                birthday = ?, notes = ?, starred = ?, photo_path = ?
            WHERE id = ?""";

        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            // 参数绑定（保持原有逻辑）
            pstmt.setString(1, contact.getName());
            pstmt.setString(2, contact.getPhone());
            pstmt.setString(3, contact.getMobile());
            pstmt.setString(4, contact.getEmail());
            pstmt.setString(5, contact.getWechat());
            pstmt.setString(6, contact.getQQ());
            pstmt.setString(10, contact.getCompany());
            pstmt.setString(11, contact.getHomeAddress());
            pstmt.setString(12, contact.getPostalCode());
            pstmt.setString(13, contact.getBirthday() != null ? contact.getBirthday().toString() : null);
            pstmt.setString(14, contact.getRemark());
            pstmt.setBoolean(15, contact.isStarred());
            pstmt.setString(16, contact.getPhotoPath());
            pstmt.setInt(17, contact.getId());

            int rowsAffected = pstmt.executeUpdate();

            return pstmt.executeUpdate() > 0;
        }
    }

    // 作用：向数据库和内存中添加联系人（重载方法）
    public void addContact(Contact contact) {
        if (contact.getName() == null || contact.getName().isEmpty() ||
                contact.getMobile() == null || contact.getMobile().isEmpty()) {
            throw new IllegalArgumentException("姓名和手机号为必填项！");
        }

        String sql = """
            INSERT INTO contacts (name, phone, mobile, email, im_WeChat, im_QQ, im_red_book, im_TikTok, im_Weibo, company, address, postal_code, birthday, notes, starred, photo_path)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
            """;

        try (Connection conn = DriverManager.getConnection(DB_URL);
             PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {

            pstmt.setString(1, contact.getName());
            pstmt.setString(2, contact.getPhone());
            pstmt.setString(3, contact.getMobile());
            pstmt.setString(4, contact.getEmail());
            pstmt.setString(5, contact.getWechat());
            pstmt.setString(6, contact.getQQ());
            pstmt.setString(10, contact.getCompany());
            pstmt.setString(11, contact.getHomeAddress());
            pstmt.setString(12, contact.getPostalCode());
            pstmt.setString(13, contact.getBirthday() != null ? contact.getBirthday().toString() : null);
            pstmt.setString(14, contact.getRemark());
            pstmt.setBoolean(15, contact.isStarred());
            pstmt.setString(16, contact.getPhotoPath());

            int rowsAffected = pstmt.executeUpdate();
            if (rowsAffected > 0) {
                ResultSet rs = pstmt.getGeneratedKeys();
                if (rs.next()) {
                    int generatedId = rs.getInt(1);
                    contact.setId(generatedId);
                    // 将新联系人添加到内存中的联系人列表
                    contacts.add(contact);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 作用：更新联系人与分组的关联关系（删除旧关系并插入新关系）
    private void updateGroupRelations(Connection conn, Contact contact) throws SQLException {
        // 删除旧关系
        try (PreparedStatement pstmt = conn.prepareStatement(
                "DELETE FROM contact_group_mapping WHERE contact_id = ?")) {
            pstmt.setInt(1, contact.getId());
            pstmt.executeUpdate();
        }

        // 插入新关系
        String insertSQL = "INSERT INTO contact_group_mapping (contact_id, group_id) VALUES (?, ?)";
        try (PreparedStatement pstmt = conn.prepareStatement(insertSQL)) {
            for (Group group : contact.getGroups()) {
                pstmt.setInt(1, contact.getId());
                pstmt.setInt(2, group.getGroupId());
                pstmt.addBatch();
            }
            pstmt.executeBatch();
        }
    }

    public interface ContactUpdateListener {
        /**
         * 联系人更新时触发的回调方法
         * @param updatedContact 更新后的联系人对象
         */
        void onContactUpdated(Contact updatedContact);
    }

    // 添加监听器列表声明
    private final ObservableList<ContactUpdateListener> contactUpdateListeners =
            FXCollections.observableArrayList();

    // 添加监听器管理方法
    public void addContactUpdateListener(ContactUpdateListener listener) {
        if (listener != null) {
            contactUpdateListeners.add(listener);
        }
    }

    // 通知所有监听器联系人信息已更新（JavaFX线程安全）
    private void notifyContactUpdate(Contact updatedContact) {
        System.out.println("开始通知联系人更新监听器，监听器数量: " + contactUpdateListeners.size());
        // 触发更新事件
        Platform.runLater(() -> {
            for (ContactUpdateListener listener : contactUpdateListeners) {
                listener.onContactUpdated(updatedContact);
            }
        });
    }

    // 查找联系人（按 ID）
    // @return 存在返回Optional<Contact>，否则返回空
    public Optional<Contact> findContactById(int id) {
        String sql = "SELECT * FROM contacts WHERE id = ?";
        try (Connection conn = DriverManager.getConnection(DB_URL);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, id);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                return Optional.of(mapResultSetToContact(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return Optional.empty();
    }

    // 查找联系人（按姓名）
    // @return 匹配的联系人列表（可能为空）
    public List<Contact> findContactsByName(String name) {
        String sql = "SELECT * FROM contacts WHERE name LIKE ?";
        List<Contact> contacts = new ArrayList<>();
        try (Connection conn = DriverManager.getConnection(DB_URL);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, "%" + name + "%");
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                contacts.add(mapResultSetToContact(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return contacts;
    }
    // 从数据库加载所有联系人到内存
    private void loadContacts() {
        getAllContacts(); // 直接调用 getAllContacts 方法
    }
    // 获取所有联系人（含分组信息）
    // @return 包含所有联系人的ObservableList
    public ObservableList<Contact> getAllContacts() {
        ObservableList<Contact> contacts = FXCollections.observableArrayList();
        String sql = """
            SELECT c.*, g.name AS group_name, g.id AS group_id
            FROM contacts c
            LEFT JOIN contact_group_mapping cgm ON c.id = cgm.contact_id
            LEFT JOIN groups g ON cgm.group_id = g.id
            """;
        try (Connection conn = DriverManager.getConnection(DB_URL);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {

            Map<Integer, Contact> contactMap = new HashMap<>();

            // 设置所有联系人信息
            while (rs.next()) {
                int contactId = rs.getInt("id");
                String name = rs.getString("name");
                String phone = rs.getString("phone");
                String mobile = rs.getString("mobile");
                String email = rs.getString("email");

                // 可选字段：如果数据库中为空，则设置为 null
                String wechat = rs.getString("im_WeChat");
                String qq = rs.getString("im_QQ");
                String company = rs.getString("company");
                String homeAddress = rs.getString("address");
                String postalCode = rs.getString("postal_code");
                String birthdayStr = rs.getString("birthday");
                String photoPath = rs.getString("photo_path");

                LocalDate birthday = null;
                if (birthdayStr != null && !birthdayStr.isEmpty()) {
                    birthday = LocalDate.parse(birthdayStr);
                }
                String remark = rs.getString("notes");
                boolean starred = rs.getInt("starred") == 1;

                // 创建或获取 Contact 对象
                Contact contact = contactMap.computeIfAbsent(contactId, k -> {
                    Contact newContact = new Contact(name, mobile);
                    newContact.setId(contactId);
                    newContact.setGroups(FXCollections.observableArrayList());
                    return newContact;
                });

                // 设置所有联系人信息
                contact.setPhone(phone);
                contact.setEmail(email);
                contact.setWechat(wechat);
                contact.setQQ(qq);
                contact.setCompany(company);
                contact.setHomeAddress(homeAddress);
                contact.setPostalCode(postalCode);
                contact.setBirthday(birthday);
                contact.setRemark(remark);
                contact.setStarred(starred);
                contact.setPhotoPath(photoPath);

                // 处理组信息
                int groupId = rs.getInt("group_id");
                String groupName = rs.getString("group_name");
                if (groupId != 0 && groupName != null && !groupName.isEmpty()) {
                    Group group = new Group();
                    group.setGroupId(groupId);
                    group.setGroupName(groupName);
                    contact.getGroups().add(group);
                }
            }

            contacts.addAll(contactMap.values());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return contacts;
    }
    // 将 数据库结果集映射为 Contact 对象
    // @return 映射后的 Contact 对象
    private Contact mapResultSetToContact(ResultSet rs) throws SQLException {
        int id = rs.getInt("id");
        String name = rs.getString("name");
        String phone = rs.getString("phone");
        String mobile = rs.getString("mobile");
        String email = rs.getString("email");

        // 可选字段：如果数据库中为空，则设置为 null
        String wechat = rs.getString("im_WeChat");
        String qq = rs.getString("im_QQ");
        String company = rs.getString("company");
        String homeAddress = rs.getString("address");
        String postalCode = rs.getString("postal_code");
        String birthdayStr = rs.getString("birthday");

        LocalDate birthday = null;
        if (birthdayStr != null && !birthdayStr.isEmpty()) {
            birthday = LocalDate.parse(birthdayStr);
        }
        String remark = rs.getString("notes");
        boolean starred = rs.getInt("starred") == 1;

        Contact contact = new Contact(name, mobile);
        contact.setId(id);
        contact.setPhone(phone);
        contact.setWechat(wechat != null ? wechat : "");
        contact.setQQ(qq != null ? qq : "");
        contact.setCompany(company != null ? company : "");
        contact.setHomeAddress(homeAddress != null ? homeAddress : "");
        contact.setPostalCode(postalCode != null ? postalCode : "");
        contact.setBirthday(birthday);
        contact.setRemark(remark != null ? remark : "");
        contact.setStarred(starred);
        contact.setPhotoPath(rs.getString("photo_path"));

        return contact;
    }

    // 获取姓名的拼音声母（每个汉字提取首字母）
    // @return 姓名的拼音声母，若姓名为空则返回 "#"
    private String getFirstLetters(String name) {
        StringBuilder sb = new StringBuilder();
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (char c : name.toCharArray()) {
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
                try {
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    if (pinyinArray != null && pinyinArray.length > 0) {
                        sb.append(pinyinArray[0].charAt(0));
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
    // 获取姓名的完整拼音（非汉字直接保留）
    // @return 全拼字符串（小写）
    private String getFullPinyin(String name) {
        StringBuilder sb = new StringBuilder();
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (char c : name.toCharArray()) {
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
                try {
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    if (pinyinArray != null && pinyinArray.length > 0) {
                        sb.append(pinyinArray[0]);
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
    // 获取姓的拼音首字母（中文转拼音首字母，其他转大写）
    // @return 姓名首字符的拼音首字母或字符大写形式，姓名为空时返回 "#"
    private String getSurnamePinyinInitial(Contact contact) {
        String name = contact.getName();
        if (name == null || name.isEmpty()) {
            return "#";
        }
        char firstChar = name.charAt(0);
        if (Character.toString(firstChar).matches("[\\u4E00-\\u9FA5]+")) {
            HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
            format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
            format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
            try {
                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(firstChar, format);
                if (pinyinArray != null && pinyinArray.length > 0) {
                    return String.valueOf(pinyinArray[0].charAt(0));
                }
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                e.printStackTrace();
            }
        }
        return Character.toString(Character.toUpperCase(firstChar));
    }
    // 按关键字搜索联系人（支持中文、数字、拼音匹配）
    // @return 匹配的联系人列表（按拼音首字母排序）
    public List<Contact> searchContacts(String keyword) {
        System.out.println("开始搜索，关键字: " + keyword);
        boolean isChinese = keyword.matches(".*[\\u4E00-\\u9FA5].*");
        boolean isNumeric = keyword.matches("\\d+");
        String sql;
        // 非中文且非数字关键字，仅查询姓名的拼音匹配，避免 SQL 中对拼音的无效查询
        if (isChinese || isNumeric) {
            sql = "SELECT * FROM contacts WHERE name LIKE ? OR phone LIKE ? OR mobile LIKE ?";
        } else {
            sql = "SELECT * FROM contacts WHERE name LIKE ?";
        }
        List<Contact> contacts = new ArrayList<>();
        try (Connection conn = DriverManager.getConnection(DB_URL);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            String likeKeyword = "%" + keyword + "%";
            if (isChinese || isNumeric) {
                pstmt.setString(1, likeKeyword);
                pstmt.setString(2, likeKeyword);
                pstmt.setString(3, likeKeyword);
            } else {
                pstmt.setString(1, "%"); // 先查询所有姓名，后续用拼音匹配
            }
            System.out.println("执行 SQL 查询: " + sql.replace("?", likeKeyword));
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                Contact contact = mapResultSetToContact(rs);
                contacts.add(contact);
                System.out.println("数据库查询结果: " + contact.getName());
            }
        } catch (SQLException e) {
            System.out.println("数据库查询出错: " + e.getMessage());
            e.printStackTrace();
        }
        List<Contact> filteredContacts = new ArrayList<>();
        for (Contact contact : contacts) {
            String firstLetters = getFirstLetters(contact.getName());
            String fullPinyin = getFullPinyin(contact.getName());
            System.out.println("联系人: " + contact.getName() + ", 声母: " + firstLetters + ", 全拼: " + fullPinyin);
            if (isChinese || isNumeric) {// 中文或数字关键字，直接使用数据库查询结果
                filteredContacts.add(contact);
                System.out.println("匹配成功: " + contact.getName());
            } else {
                // 拼音关键字，进行拼音匹配
                if (firstLetters.startsWith(keyword.toLowerCase()) || fullPinyin.startsWith(keyword.toLowerCase())) {
                    filteredContacts.add(contact);
                    System.out.println("拼音匹配成功: " + contact.getName());
                }
            }
        }
        // 按姓的拼音首字母排序
        filteredContacts.sort(Comparator.comparing(this::getSurnamePinyinInitial).thenComparing(Contact::getName));
        System.out.println("搜索结束，匹配结果数量: " + filteredContacts.size());
        return filteredContacts;
    }

    // 按分组查询该组内的所有联系人
    // @return 该分组下的联系人列表
    public List<Contact> getContactsByGroup(Group group) {
        return getAllContacts().stream()
                .filter(contact -> contact.getGroups().contains(group))
                .collect(Collectors.toList());
    }
    
}